package com.syl.springcloud.security.config.listener;

import com.syl.springcloud.security.config.util.CommonUtils;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.MutablePropertySources;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @author syl
 * @create 2018-08-02 11:44
 **/
public class securityConfigListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {

    @Override
    public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
        ConfigurableEnvironment environment = event.getEnvironment();
        MutablePropertySources propertySources = environment.getPropertySources();
        Map<String, Object> myMap = new HashMap();

        Properties properties = CommonUtils.getFileProperties("authorization-config.properties");
        // 设置cookie名称 避免一样导致冲突
//        myMap.put("server.servlet.session.cookie.name", System.currentTimeMillis()+"_SESSION");
        myMap.put("security.oauth2.client.client-id", properties.getProperty("authorization.clientId"));
        myMap.put("security.oauth2.client.client-secret", properties.getProperty("authorization.secret"));
        String uri = properties.getProperty("authorization.oauthCentreUri");
        myMap.put("security.oauth2.client.access-token-uri", uri+"/oauth/token");
        myMap.put("security.oauth2.client.user-authorization-uri", uri+"/oauth/authorize");
        // 不需要统一配置场景 各客户端应该各自配置自己的场景值
//        List<String> scopes = CommonUtils.getPropertiesList(properties, "scope");
//        for (int i = 0; i < scopes.size(); i++) {
//            String scope = scopes.get(i);
//            myMap.put("security.oauth2.client.scope["+i+"]",scope);
//        }
        myMap.put("security.oauth2.resource.user-info-uri", uri+"/user/info");
        propertySources.addFirst(new MapPropertySource("mySecurityConfig", myMap));
    }

}
